<template>
    <Page>
        <Topbar hideMenu />
        <Content>
            <Panel>
                <view class="left">
                    <MyInfo :data="workInfo" backUrl="/pages/workbench/bad/index" />
                </view>
                <Empty v-if="!isValid" />
                <FormWrap header title="不良操作" height="80vh" v-if="isValid">
                    <u--form :labelPosition="labelPosition" labelAlign="left" :model="model" :rules="rules" ref="uForm"
                        labelWidth="14rem" :labelStyle="{'margin-bottom' : labelPosition === 'top' ? '2rem' : '0'}"
                        style="padding: 0 5rem;">
                        <u-form-item label="处理结果" prop="checkResult">
                            <u-radio-group v-model="model.checkResult" placement="row" @change="clickCheckResult">
                                <u-radio v-for="(item, index) in ['合格', '报废', '返工', '不合格入库']" :key="index" :label="item"
                                    :name="item">
                                </u-radio>
                            </u-radio-group>
                        </u-form-item>
                        <view class="sub-title">
                            处理结果
                        </view>
                        <u-row justify="space-between">
                            <u-col span="5">
                                <u-form-item label="班次时间" prop="shiftTime" required class="label-fwn">
                                    <DatePicker v-model="model.shiftTime" @change="shiftTimeChange" />
                                </u-form-item>
                            </u-col>
                            <u-col span="5">
                                <u-form-item label="班次" prop="shiftId" required class="label-fwn">
                                    <SingleSelect v-model="model.shiftId" :list="shifts" mode="single" />
                                </u-form-item>
                            </u-col>
                        </u-row>
                        <u-row justify="space-between">
                            <u-col span="5">
                                <u-form-item label="提报方式" prop="warehousingMethod" required class="label-fwn">
                                    <uni-data-select v-model="model.warehousingMethod"
                                        :modelValue="model.warehousingMethod" :localdata="reportingMethods"
                                        format="{label}" :clear="false" placeholder="请选择"></uni-data-select>
                                </u-form-item>
                            </u-col>
                            <u-col span="5">
                                <u-form-item :label="getLabel()" prop="inNum" required class="label-fwn">
                                    <InputNumberField v-model.number="model.inNum" :min="0" :max="999999"
                                        :placeholder="model.checkResult === '报废'? '自动计算' : '请输入'"
                                        :disabled="model.checkResult === '报废'">
                                        <template slot="suffix" v-if="model.warehousingMethod==='按重量'">
                                            {{ workInfo.weightUnit }}
                                        </template>
                                    </InputNumberField>
                                </u-form-item>
                            </u-col>
                        </u-row>
                        <u-row justify="space-between">
                            <u-col span="5" v-if="model.checkResult !== '报废' && model.checkResult !== '返工'">
                                <u-form-item label="入库仓库" prop="inWarehouseId" required class="label-fwn">
                                    <SingleSelect v-model="model.inWarehouseId" :list="wareHouses" mode="single" />
                                </u-form-item>
                            </u-col>
                            <u-col span="5">
                                <u-form-item label="备注" prop="remarks" class="label-fwn">
                                    <InputField v-model="model.remarks" :maxlength="100" />
                                </u-form-item>
                            </u-col>
                        </u-row>
                        <u-form-item label="报废原因" prop="outReason" class="label-top" v-if="model.checkResult === '报废'">
                            <u-radio-group v-model="model.outReason" placement="row">
                                <u-radio v-for="(item, index) in reasons" :key="index" :label="item.label"
                                    :name="item.value">
                                </u-radio>
                            </u-radio-group>
                        </u-form-item>
                        <view class="sub-title" v-if="model.checkResult === '报废'">
                            不良项
                        </view>
                        <view class="ng-list" v-if="model.checkResult === '报废'">
                            <u-form-item v-for="(item, index) in ngList" :key="index" :label="item.ngCode"
                                class="label-fwn">
                                <InputNumberField v-model.number="item.ngNumber" placeholder="请输入数量" :min="0"
                                    :max="999999" @blur="autoTotal" />
                            </u-form-item>
                        </view>
                        <u-form-item label="上传图片" prop="imagePath">
                            <ImageUpload v-model="model.imagePath" />
                        </u-form-item>
                    </u--form>
                    <template slot="footer">
                        <Button large @click="open2">
                            历史报废记录
                        </Button>
                        <Button large type="primary" @click="open1" style="margin-left: 3rem;">
                            提交
                        </Button>
                    </template>
                </FormWrap>
            </Panel>
        </Content>
        <Modal title="历史不良记录" ref="popup2" width="80%" noComfirm>
            <view class="table-demo">
                <Table ref="table" :columns="columns" :src="src" :params="params" pagination />
            </view>
        </Modal>
        <Modal title="确认提交吗？" ref="popup1" @confirm="confirm1" />
    </Page>
</template>

<script>
    import Page from "@/components/page/index.vue";
    import Topbar from "@/components/topbar/index.vue";
    import Content from "@/components/content/index.vue";
    import Panel from "@/components/panel/index.vue";
    import Empty from "@/components/empty/index.vue";
    import Button from "@/components/button/index.vue";
    import FormWrap from '@/components/formWrap/index.vue';
    import InputField from '@/components/formField/inputField/index.vue';
    import InputNumberField from '@/components/formField/inputNumberField/index.vue';
    import DatePicker from '@/components/formField/datePicker/index.vue';
    import ImageUpload from '@/components/formField/imageUpload/index.vue';
    import SingleSelect from '@/components/formField/singleSelect/index.vue';
    import Modal from '@/components/modal/index.vue';
    import Table from '@/components/table/index.vue';
    import fetch from "@/utils/fetch";
    import MyInfo from "./info/index.vue";
    import {
        getDevice
    } from "@/store/user.js";
    import filter from "@/utils/filter";
    import {
        timeIsBetweenTimeRange
    } from "@/utils/date";

    export default {
        components: {
            Page,
            Topbar,
            Content,
            Panel,
            Empty,
            Button,
            FormWrap,
            InputField,
            InputNumberField,
            DatePicker,
            ImageUpload,
            Modal,
            Table,
            MyInfo,
            SingleSelect
        },
        data() {
            return {
				defectiveNumber:'',
                isValid: false, // 界面是否可用                
                workInfo: {},
                labelPosition: 'left',
                shifts: [],
                reportingMethods: [{
                        label: '按数量',
                        value: '按数量',
                    },
                    {
                        label: '按重量',
                        value: '按重量',
                    }
                ],
                wareHouses: [],
                reasons: [],
                model: {
                    checkResult: '合格',
                    shiftId: '',
                    shift: '',
                    shiftTime: Number(new Date()),
                    warehousingMethod: '按数量',
                    inNum: '',
                    inWarehouseId: '',
                    inWarehouseName: '',
                    outReason: '',
                    imagePath: []
                },
                ngList: [],
                rules: {
                    'shiftId': {
                        type: 'number',
                        required: true,
                        message: '必填项',
                        trigger: ['blur', 'change']
                    },
                    'warehousingMethod': {
                        type: 'string',
                        required: true,
                        message: '必填项',
                        trigger: ['blur', 'change']
                    },
                    'inWarehouseId': {
                        type: 'number',
                        required: true,
                        message: '必填项',
                        trigger: ['blur', 'change']
                    },
                    'inNum': {
                        type: 'number',
                        required: true,
                        message: '必填项',
                        trigger: ['blur', 'change']
                    },
                },
                src: '/dms/mobileEnd/getHistory',
                params: {},
                columns: [{
                    label: '生产班次',
                    value: 'shift',
                }, {
                    label: '提报数量',
                    value: 'inNum',
                }, {
                    label: '类型',
                    value: 'workCode',
                }, {
                    label: '类型',
                    value: 'checkResult',
                }, {
                    label: '操作工',
                    value: 'workStartTime',
                }, {
                    label: '提报时间',
                    value: 'reportingTime',
                }],
            }
        },
        methods: {
            getLabel() {
                if (this.model.warehousingMethod === '按数量') {
                    if (this.model.checkResult === '合格' || this.model.checkResult === '不合格入库') {
                        return '入库数量';
                    }
                    if (this.model.checkResult === '报废') {
                        return '报废数量';
                    }
                    if (this.model.checkResult === '返工') {
                        return '返工数量';
                    }
                } else {
                    if (this.model.checkResult === '合格' || this.model.checkResult === '不合格入库') {
                        return '入库重量';
                    }
                    if (this.model.checkResult === '报废') {
                        return '报废重量';
                    }
                    if (this.model.checkResult === '返工') {
                        return '返工重量';
                    }
                }
            },
            getWorkOrderInfo(workOrder) {
                fetch('get', '/dms/mobileEnd/getWorkSelfCheckList', {
                    workOrder,
					defectiveNumber:this.defectiveNumber,
                }).then((res) => {
                    this.isValid = true;
                    this.workInfo = res;
                    this.params.workOrder = res.workCode;
                    this.params.defectiveNumber = this.defectiveNumber;
                    this.getShiftList();
                    this.getWareHouses();
                    this.getOutReasons();
                    this.getPoorList();
                }).catch(() => {
                    this.isValid = false;
                });
            },
            clickCheckResult() {
                //清空数量
                this.model.inNum = '';
                //报废自动计算数量
                if (this.model.checkResult === '报废') {
                    this.autoTotal();
                }
                this.model.inWarehouseId = '';
                this.model.inWarehouseName = '';
                this.wareHouses = [];
                this.getWareHouses();
            },
            // 根据不良项数量 自动计算数量
            autoTotal() {
                let total = 0;
                this.ngList.forEach((item) => {
                    total += item.ngNumber;
                });
                this.model.inNum = total;
            },
            open1() {
                this.$refs['uForm'].validate().then((valid) => {
                    if (valid) this.$refs.popup1.open()
                });
            },
            open2() {
                this.$refs.popup2.open()
                setTimeout(() => {
                    this.$refs['table'] && this.$refs['table'].reload();
                }, 100)
            },
            confirm1() {
                const {
                    checkResult,
                    shiftId,
                    shiftTime,
                    warehousingMethod,
                    inNum,
                    inWarehouseId,
                    outReason,
                    imagePath
                } = this.model;
                const data = {
                    checkResult,
                    shiftId,
                    shift: this.shifts.find(item => item.value === shiftId).label,
                    shiftTime: this.dayjs(shiftTime).format('YYYY-MM-DD'),
                    warehousingMethod,
                    inNum,
                    inWarehouseId,
                    inWarehouseName: this.wareHouses.find(item => item.value === inWarehouseId).label,
                    workCode: this.workInfo.workCode,
                    imagePath,
					defectiveNumber:this.defectiveNumber,
                };
                if (checkResult === '报废') {
                    data.outReason = outReason;
                }
                fetch('post', '/dms/mobileEnd/addWorkSelfCheck', null, data).then(() => {
                    this.$toast('提交成功');
                    this.goto('/pages/workbench/bad/index');
                });
            },
            goto(url) {
                uni.navigateTo({
                    url,
                    animationType: "pop-in",
                    animationDuration: 1000,
                })
            },
            getOutReasons() {
                fetch("get", "/dms/faultCategory/dictList", {
                    name: "报废",
                }).then((res) => {
                    this.reasons = res.map(item => {
                        return {
                            label: item.value,
                            value: item.value
                        }
                    });
                    if (this.reasons.length !== 0)
                        this.model.outReason = this.reasons[0].value;
                });
            },
            shiftTimeChange() {
                this.model.shift = null;
                this.getShiftList();
            },
            getShiftList() {
                fetch("get", "/dms/mobile/getShiftList", {
                    deviceNo: getDevice().deviceNo,
                    shiftDate: this.dayjs(this.model.shiftTime).format('YYYY-MM-DD'),
                }).then((res) => {
                    this.shifts = res.map((item) => ({
                        label: item.shift,
                        value: item.shiftId,
                    }));
                    if (this.shifts.length !== 0) {
                        const has = res.find(item => timeIsBetweenTimeRange(filter.formatCurrentTimeDuration(),
                            item.shiftStartTime,
                            item.shiftEndTime));
                        if (has)
                            this.model.shiftId = has.shiftId;
                        else
                            this.model.shiftId = this.shifts[0].value;
                    }
                });
            },
            getWareHouses(value) {
                let url = '/dms/mobileEnd/getQualifiedWarehouse';
                if (this.model.checkResult === '不合格入库') {
                    url = '/dms/mobileEnd/getDefectiveWarehouse';
                }
                fetch("get", url, {
                    deviceNo: getDevice().deviceNo,
                }).then((res) => {
                    if (res) {
                        this.wareHouses = [{
                            label: res.backupName,
                            value: res.id,
                        }];
                        if (this.wareHouses.length !== 0) {
                            this.model.inWarehouseId = this.wareHouses[0].value;
                        }
                    }
                });
            },
            getPoorList() {
                fetch("get", "/dms/faultCategory/dictList", {
                    name: "不良项",
                }).then((res) => {
                    this.ngList = res.map(item => {
                        return {
                            ngCode: item.value,
                            ngNumber: 0,
                        }
                    });
                });
            },
        },
        onLoad(params) {
			this.defectiveNumber=params.defectiveNumber;
            this.getWorkOrderInfo(params.workCode);
        }
    };
</script>

<style scoped lang="scss">
    .left {
        flex: 0 auto;
        width: 50rem;
        background: #f8f8fa;
    }

    .right {
        flex: 1;
        background-color: red;
        background: #fff;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: center;
        padding: 3rem 4rem 5rem;
    }

    .ng-list {
        display: flex;
        flex-wrap: wrap;

        /deep/ .u-form-item {
            width: 45%;
            margin-left: 3%;
        }
    }

    .label-fwn {
        /deep/ .u-form-item__body__left__content__label {
            font-weight: normal !important;
        }
    }

    .sub-title {
        padding: 3rem 0;
        font-size: 2.2rem;
        font-weight: bold;
        border-bottom: 1px solid #ccc;
        margin: 2rem 0;
    }

    /deep/ .form-wrap .body {
        padding-top: 0;
    }

    .label-top {
        /deep/ .u-form-item__body__left {
            align-items: flex-start !important;
            margin-top: 2.7rem;
        }
    }

    .label-fwn {
        /deep/ .u-form-item__body__left__content__label {
            font-weight: normal !important;
        }
    }

    .table-demo {
        flex: 1;
        display: flex;
		overflow: hidden;
        flex-direction: column;
    }
</style>